import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { uniqueId } from 'lodash';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { DatatableComponent } from '@iux/live';

@Component({
  selector: 'app-drag-and-drop',
  templateUrl: './drag-and-drop.component.html',
  styles: [
    `
      .cdk-drop-list-dragging tr:not(.cdk-drag-placeholder) {
        transition: transform 200ms cubic-bezier(0, 0, 0.2, 1);
      }
      .cdk-drag-animating {
        transition: transform 200ms cubic-bezier(0, 0, 0.2, 1);
      }
      .cdk-drag-placeholder {
        height: 40px;
        border: 1px dashed #2673e5;
        border-radius: 4px;
      }
      .cdk-drag-preview {
        display: flex;
        border-radius: 4px;
        background-color: #f2f2f2;
      }
      .cdk-drag-preview td {
        flex: 1;
        padding: 0 8px;
        line-height: 40px;
        text-align: left;
      }
      .cdk-drag-preview td:first-child {
        padding-left: 16px;
      }
      .cdk-drag-preview td:last-child {
        padding-right: 16px;
      }
      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DragAndDropComponent implements OnInit {
  data;
  @ViewChild(DatatableComponent, { static: true }) lvTable: DatatableComponent;
  constructor() {}

  ngOnInit() {
    this.initData();
  }

  drop(event: CdkDragDrop<string[]>) {
    // P.S. renderData 和 data不是一个地址
    moveItemInArray(this.lvTable.renderData, event.previousIndex, event.currentIndex);

    moveItemInArray(this.lvTable.lvData, event.previousIndex, event.currentIndex);
  }

  initData() {
    this.data = Array.from({ length: 40 }).map((item, key) => this.initUser(key));
  }

  initUser(key: number) {
    return { id: uniqueId('uid'), name: `user${key}`, age: 10 + key };
  }
}
